import Vue from 'vue'
import VueRouter from 'vue-router'

// 导入Login登录组件
import Login from '../views/Login.vue'

// 导入Home主页组件
import Home from '../views/Home.vue'

// 导入 Welcome组件
import Welcome from '../views/Welcome.vue'

// 导入User组件 @是vue提供的一个简写方式 后面必须要加斜线 代表src目录
import User from '@/views/Users/Userlist.vue'

// 导入rights权限组件
import Rights from '../views/power/Rights.vue'

// 导入Roles组件
import Roles from '../views/power/Roles.vue'

// 导入Category组件
import Category from '../views/Goods/Category.vue'

// 导入Params组件
import Params from '../views/Goods/Params.vue'

// 导入GoodList组件
import GoodList from '../views/Goods/GoodList.vue'

// 导入addgoods组件
import Add from '@/views/Goods/Add.vue'

// 导入OrderList组件
import OrderList from '@/views/Orders/OrderList.vue'

// 导入Report组件
import Report from '@/views/Report/Report.vue'

Vue.use(VueRouter)

const routes = [
  // 路由重定向
  { path: '/', redirect: '/login' },
  // 配置登录路由规则
  { path: '/login', component: Login },
  // 在home的children中配置路由规则
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: User },
      { path: '/rights', component: Rights },
      { path: '/roles', component: Roles },
      { path: '/categories', component: Category },
      { path: '/params', component: Params },
      { path: '/goods', component: GoodList },
      { path: '/goods/addgood', component: Add },
      { path: '/orders', component: OrderList },
      { path: '/reports', component: Report }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 挂在路由导航守卫 用户没有登录禁止访问页面的内容 从而保证安全性
// to -- 要跳转的地址
// from -- 当前导航正要离开的路由
// next -- 放行，执行下一步操作
router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    return next()
  }
  // 获取token，如果token值是null，说明用户没有登录，否则用户处在登陆状态
  const myToken = window.sessionStorage.getItem('token')

  // 上一步获取到了token的值，开始跟还有token的值做判断
  // 如果不存在token，返回的是null
  if (!myToken) {
    return next('/login')
  }

  next()
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
export default router
